﻿using System;
using System.Collections.Generic;
using System.Threading;
using NUnit;
using NUnit.Framework;
using Rhino.Mocks;
using System.Globalization;
using System.Resources;
using System.Linq.Expressions;
using System.Reflection;
using System.Diagnostics;

namespace mForum.Core.Tests.Infrastructure.Validation
{
    using mForum.Resources;
    using mForum.Core.Infrastructure.Resource;
    using mForum.Core.Infrastructure.Validation;

    [TestFixture]
    public class ValidationTest
    {
        private ResourceManager _resourceManager;
        private ResourceManagerFactory _resourceManagerFactory;

        [SetUp]
        public void Setup()
        {
            _resourceManagerFactory = new ResourceManagerFactory();
            _resourceManager = _resourceManagerFactory.CreateResourceManager();

            ResourceHelper.Initialize(_resourceManager);
        }

        [Test]
        [TestCase("", 60, 2)]
        [TestCase("", 30, 1)]
        [TestCase("Test", 12, 0)]
        [TestCase("", 75, 3)]
        public void can_validate_object(string name, int age, int expectedErrorCount)
        {
            int expectedErrors = expectedErrorCount;

            TestEntity entity = new TestEntity()
            {
                Name = name,
                Age = age
            };

            ValidationResult validationResult = entity.Validate();

            Assert.AreEqual(expectedErrorCount, validationResult.CountErrors());
        }

        [Test]
        public void can_retrive_field_name_from_lamba_expression()
        {
            string expectedfieldName = "Name";

            TestEntity entity = new TestEntity()
            {
                Name = "",
                Age = 20
            };

            ValidationResult validationResult = entity.Validate();

            Assert.IsTrue(validationResult.Errors.ContainsKey(expectedfieldName));
        }
    }

    public class TestEntity : IValidatable
    {
        public string Name;
        public int Age;

        public ValidationResult Validate()
        {
            ValidationResult validationResult = new ValidationResult();
            ValidationHelper<TestEntity> validationHelper = new ValidationHelper<TestEntity>();

            validationResult.AddError(validationHelper.CreateErrorIf(!(String.IsNullOrEmpty(Name)), f=> f.Name, ResourceKey.Common.RequiredField));

            validationResult.AddError(validationHelper.CreateErrorIf(Age < 50, f => f.Age, ResourceKey.Common.InvalidMessage));
            validationResult.AddError(validationHelper.CreateErrorIf(Age < 70, f => f.Age, ResourceKey.Common.InvalidEmail));

            return validationResult;
        }
    }
}
